package DAO

import (
	"CSMS/database"
	"fmt"
)

type Discount struct {
	MinMoney     int     `db:"MinMoney"`
	MaxMoney     int     `db:"MaxMoney"`
	DiscountRate float64 `db:"DiscountRate"`
}

//judgeDiscount 判断金额该打多少折
func JudgeDiscount(indentTotalPrice int) float64 {
	//首先按顺序从discount表中获取打折
	rows, err := database.DB.Query("SELECT * FROM discount")
	defer func() {
		if rows != nil {
			rows.Close() //可以关闭掉未scan连接一直占用
		}
	}()
	if err != nil {
		fmt.Printf("Query failed,err:%v", err)
		return 0
	}
	var discount Discount
	for rows.Next() {
		err = rows.Scan(&discount.MinMoney, &discount.MaxMoney, &discount.DiscountRate)
		if err != nil {
			fmt.Printf("Scan failed,err:%v", err)
			return 0
		}
		if indentTotalPrice >= discount.MinMoney && indentTotalPrice <= discount.MaxMoney {
			return discount.DiscountRate
		}
	}
	return 0
}

//SelectDiscountList 获取金额列表
func SelectDiscountList() []Discount {
	var discountList []Discount
	//首先按顺序从discount表中获取打折
	rows, err := database.DB.Query("SELECT * FROM discount")
	defer func() {
		if rows != nil {
			rows.Close() //可以关闭掉未scan连接一直占用
		}
	}()
	if err != nil {
		fmt.Printf("Query failed,err:%v", err)
		return discountList
	}
	var discount Discount
	for rows.Next() {
		err = rows.Scan(&discount.MinMoney, &discount.MaxMoney, &discount.DiscountRate)
		if err != nil {
			fmt.Printf("Scan failed,err:%v", err)
			return discountList
		}
		discountList = append(discountList, discount)
	}
	return discountList
}
